﻿using System.Configuration;
using Newtonsoft.Json;

public class SendTemplateMessageService
{
    /// <summary>
    /// 公众号相关信息
    /// </summary>
    private  string AppId = ConfigurationManager.AppSettings["appid"];
    private  string AppSecret = ConfigurationManager.AppSettings["appsecret"];

    /// <summary>
    /// 发送模板消息API
    /// </summary>
    private const string SendMessageApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

    /// <summary>
    /// 公众号发送模板消息方法
    /// </summary>
    /// <param name="appId"></param>
    /// <param name="appSecret"></param>
    /// <param name="templateId">模板ID</param>
    /// <param name="openId">微信openId</param>
    /// <param name="url">点击详情跳转路径</param>
    /// <param name="data"></param>
    public static void SendTemplateMessage(string templateId, string openId, string url, string accessToken, object data)
    {
        var sendUrl = string.Format(SendMessageApi, accessToken);
        var msg = new TemplateMessage
        {
            template_id = templateId,
            touser = openId,
            url = url,
            data = data
        };

        //序列化实体为json
        string json = JsonConvert.SerializeObject(msg, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

        //调用消息发送接口
        var result = HttpClientHelper.PostResponse<TemplateMessageResult>(string.Format(sendUrl, accessToken), json);
        //LoggerHelper.Log(string.Format("【微信公众号发送模板消息接口调用】返回参数:errcode:{0},erromsg:{1},misgid:{2}", result.errcode, result.errmsg, result.msgid));
    }
}
